package com.itheima.stock.service.impl;

import com.google.common.base.Strings;
import com.itheima.stock.mapper.SysUserMapper;
import com.itheima.stock.pojo.SysUser;
import com.itheima.stock.service.UserService;
import com.itheima.stock.utils.IdWorker;
import com.itheima.stock.vo.R;
import com.itheima.stock.vo.ResponseCode;
import com.itheima.stock.vo.req.LoginReqVo;
import com.itheima.stock.vo.res.LoginRespVo;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public R<LoginRespVo> login(LoginReqVo loginReqVo) {
        if (loginReqVo == null || Strings.isNullOrEmpty(loginReqVo.getUsername())
                || Strings.isNullOrEmpty(loginReqVo.getPassword())
                || Strings.isNullOrEmpty(loginReqVo.getRkey())
        ) {
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        //根据回传的rkey来获取redis中的验证码
        String rCode = (String) redisTemplate.opsForValue().get(loginReqVo.getRkey());
        //判断前端回传的验证码和redis中存的是否一致
        if (Strings.isNullOrEmpty(rCode) || !rCode.equals(loginReqVo.getCode())) {
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        //一致就可以正常删除,或者直接等过期自动删除
        redisTemplate.delete(loginReqVo.getRkey());
        //根据用户名查询用户信息
        SysUser userInfo = sysUserMapper.findUserByUserName(loginReqVo.getUsername());
        //判断用户是否存在，存在则密码校验比对
        if (userInfo == null || !passwordEncoder.matches(loginReqVo.getPassword(), userInfo.getPassword())) {
            return R.error(ResponseCode.SYSTEM_PASSWORD_ERROR.getMessage());
        }
        //组装登录成功数据
        LoginRespVo loginRespVo = new LoginRespVo();
        BeanUtils.copyProperties(userInfo, loginRespVo);
        return R.ok(loginRespVo);
    }

    //总体处理获取出想要的验证码和保存在redis中唯一的id
    @Override
    public R<Map> generateCaptcha() {
        //1.生成4位数字验证码
        String checkCode = RandomStringUtils.randomNumeric(4);
        //2.获取全局唯一id
        String rkey = String.valueOf(idWorker.nextId());
        //验证码存入redis中，并设置有效期1分钟
        redisTemplate.opsForValue().set(rkey, checkCode, 60, TimeUnit.SECONDS);
        //3.组装数据
        Map<String, String> map = new HashMap<>();
        map.put("code", checkCode);
        map.put("rkey", rkey);
        return R.ok(map);
    }
}
